import {
	defineComponent,
	ref,
	unref,
	watchEffect,
	toRaw,
	watch,
	onMounted,
} from 'vue'
import './style.less'
import Video from 'video.js'
import { useStore } from 'vuex'
import { CloseOutlined } from '@ant-design/icons-vue'
import { useFullscreen } from 'ahooks-vue'
import 'video.js/dist/video-js.css'
import { message } from 'ant-design-vue'
import Rectangle from '../../../assets/images/Rectangle.png'
import store from '@/store'
import { JSONCopy } from '@byteluck-fe/global-shared'
import { apiInit } from '@/services'
const POPUP_VIDEO = 'pok-prpup-video_1'
const CLNM = 'pok-prpup-video'
import { useEventListener } from '@/hooks/useEventListener'

//全屏下的样式
const fullStyle: { [key: string]: string } = {
	objectFit: 'contain',
	position: 'fixed !important',
	top: '0px !important',
	right: ' 0px !important',
	bottom: '0px !important',
	left: ' 0px !important',
	boxSizing: 'border-box !important',
	minWidth: ' 0px !important',
	maxWidth: 'none !important',
	minHeight: ' 0px !important',
	maxHeight: 'none !important',
	width: '100% !important',
	height: '100% !important',
	transform: 'none !important',
	margin: ' 0px !important',
}
//是否为safari浏览器
const isSafari = () =>
	/Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)
type EleType = HTMLElement | HTMLInputElement | null
const PopupVideo = defineComponent({
	name: 'pok-prpup-video',
	props: {
		setDropdown: {
			type: Function,
			require: false,
		},
		dropdown: {
			type: Boolean,
			require: true,
		},
	},
	setup(props, context) {
		const { commit, state } = useStore()
		const api = apiInit()
		const FullNavRef = ref<ElRef>(null)
		const visible = ref(false)
		const videoNewEl: any = ref(null)
		const showTime = ref({
			current: '00:00:00',
			duration: '',
		})
		const avatarStyle = ref({
			left: '0px',
			top: '0px',
		})
		const playStatus = ref(true) //视频是否播放
		const contentRef = ref<EleType>(null)
		const { isFullscreen, toggleFull } = useFullscreen(contentRef as any)
		const fullNavHeight = ref()
		const showScroll = (is?: boolean) =>
			(document.body.style.overflow = is ? 'auto' : 'hidden')
		//s转为时分秒
		const formatSeconds = (value: number) => {
			let result = parseInt(value)
			let h =
				Math.floor(result / 3600) < 10
					? '0' + Math.floor(result / 3600)
					: Math.floor(result / 3600)
			let m =
				Math.floor((result / 60) % 60) < 10
					? '0' + Math.floor((result / 60) % 60)
					: Math.floor((result / 60) % 60)
			let s =
				Math.floor(result % 60) < 10
					? '0' + Math.floor(result % 60)
					: Math.floor(result % 60)
			return `${h}:${m}:${s}`
		}

		//初始化播放器
		const showPlayVideo = async () => {
			showScroll()
			fullNavHeight.value =
				(unref(contentRef)!.clientWidth / 16) * 9 - 22 + 'px'
			const params = {
				controls: true,
				poster: Rectangle,
				language: 'zh-CN',
				preload: 'auto',
				controlBar: {
					// playToggle: false,
					// 竖直的音量控制
					volumePanel: false,
					// fullscreenToggle: false,
					currentTime: false,
					currentTimeDisplay: false,
					timeDivider: false,
					durationDisplay: false,
					// remainingTimeDisplay: false, //当前播放时间
					autoPlay: true,
					muted: true,
				},
			}
			try {
				videoNewEl.value = Video(POPUP_VIDEO, params)
				showTime.value = {
					current: '00:00:00',
					duration: formatSeconds(unref(videoNewEl)?.cache_?.duration),
				}
				unref(videoNewEl).play()
			} catch (e) {
				message.error('视频加载失败了，请刷新页面重试')
			}
		}
		const close = async () => {
			if (unref(isFullscreen)) {
				fullOption()
			} else {
				await api.baseAuto.AddGuideUserPrivateV1POST({
					payload: ['portal1', 'new_user_guide'],
				})
				showScroll(true)
				visible.value = false
				commit('setShowVideo', false)
				props?.setDropdown?.(undefined)
			}
		}
		onMounted(() => {
			if (unref(visible)) {
				showPlayVideo()
				mountedVideo()
			}
		})
		watchEffect(async () => {
			if (props.dropdown) {
				showScroll()
			}
			if (state.showVideo) {
				visible.value = true
			}
		})
		//判断是否全屏
		const checkFullScreen = () => {
			const doc = document as any
			return (
				doc.webkitIsFullScreen ||
				doc.fullscreen ||
				doc.mozFullScreen ||
				doc.msFullscreenElement ||
				doc.mozFullScreenEnabled
			)
		}
		//监听是否全屏模式下
		watch(
			[isFullscreen, () => checkFullScreen(), () => isSafari()],
			([isFullscreen, checkFullScreen, isSafari]) => {
				const doc = document as any
				if (isSafari) {
					editStyleVideo(checkFullScreen ? 'block' : 'none')
				}
				doc.querySelector('.vjs-control-bar')!.style!.background =
					checkFullScreen || !isSafari ? '#fff' : 'none'
				doc.querySelector('.vjs-control-bar')!.style!.width =
					checkFullScreen || !isSafari ? '100%' : 'calc(100% + 54px)'
				doc.querySelector('.vjs-control-bar')!.style!.left =
					checkFullScreen || !isSafari ? 0 : '-27px'
				if (!isFullscreen && !isSafari) {
					doc.querySelector('.vjs-control-bar')!.style!.width =
						'calc(100% + 54px)'
					doc.querySelector('.vjs-control-bar')!.style!.left = '-27px'
					doc.querySelector('.vjs-control-bar')!.style!.background = 'none'
				}
				//修改全屏模式下播放器的border-radius
				;(document.querySelector('.video-js') as any)!.style!.borderRadius =
					isFullscreen ? 0 : '8px'
				;(document.querySelector('.vjs-control-bar') as any)!.style!.bottom =
					isFullscreen ? 0 : '-30px'
			}
		)
		//播放按钮
		const playVieo = async () => {
			unref(playStatus) ? unref(videoNewEl).pause() : unref(videoNewEl).play()
			playStatus.value = !unref(playStatus)
		}
		// 音量键的开启关闭
		const adjustVolume = () => {
			unref(videoNewEl).muted(!unref(videoNewEl).muted())
		}
		const mountedVideo = () => {
			//监听视频播放时间
			unref(videoNewEl)?.on('timeupdate', () => {
				//判断用户是否在暂停时拖动进度条
				if (
					!unref(playStatus) &&
					unref(showTime).current !=
						formatSeconds(unref(videoNewEl)?.currentTime())
				) {
					unref(videoNewEl).play()
					playStatus.value = true
				}
				showTime.value = {
					current: formatSeconds(unref(videoNewEl)?.currentTime()),
					duration: formatSeconds(unref(videoNewEl)?.duration()),
				}
				if (unref(videoNewEl)?.currentTime() >= unref(videoNewEl)?.duration()) {
					playVieo()
				}
			})
			//监听屏幕尺寸发生变化时
			!unref(isFullscreen) &&
				useEventListener({
					name: 'resize',
					listener: () => {
						fullNavHeight.value =
							(unref(FullNavRef)!.clientWidth / 16) * 9 + 'px'
					},
				})
			//键盘快进 后退 暂停
			window.addEventListener('keydown', event => {
				let e = event?.keyCode
				switch (e) {
					case 32:
						playVieo()
						break
					case 37:
						videoNewEl?.value?.currentTime(
							unref(videoNewEl)?.currentTime() - 10 || 0
						)
						break //后退
					case 39:
						videoNewEl?.value?.currentTime(
							unref(videoNewEl)?.currentTime() + 10
						)
						break //前进
				}
			})
			//阻止videojs控件操作栏 父元素冒泡事件
			document
				.querySelector('.vjs-control-bar')
				?.addEventListener('click', e => e.stopPropagation())
		}
		//safari浏览器显示时间全屏 并且播放声音
		const editStyleVideo = (display = 'block') => {
			try {
				const doc = document as any

				const stylebar: EleType[] = [
					document.querySelector('.vjs-remaining-time'),
					document.querySelector('.vjs-fullscreen-control'),
					document.querySelector('.vjs-play-control'),
				]
				stylebar.map((i: EleType) => {
					i ? (i!.style!.display = display) : null
				})
			} catch (e) {
				console.log(e)
			}
		}
		//全屏事件
		const fullOption = () => {
			if (isSafari()) {
				unref(videoNewEl).requestFullscreen()
				unref(videoNewEl).muted()
			} else {
				toggleFull()
			}
		}
		return {
			visible,
			close,
			dropdown: props.dropdown,
			avatarStyle,
			playVieo,
			playStatus,
			toggleFull,
			fullOption,
			videoNewEl,
			adjustVolume,
			FullNavRef,
			isFullscreen,
			formatSeconds,
			showTime,
			fullNavHeight,
			contentRef,
		}
	},
	render() {
		const {
			visible,
			close,
			dropdown,
			avatarStyle,
			playVieo,
			playStatus,
			toggleFull,
			fullOption,
			adjustVolume,
			isFullscreen,
			formatSeconds,
			showTime,
			FullNavRef,
			fullNavHeight,
			videoNewEl,
		} = this
		const child = visible && (
			<div class={CLNM}>
				<div
					class={`${CLNM}-content`}
					style={isFullscreen ? fullStyle : {}}
					ref="contentRef"
				>
					<div class={`${CLNM}-header`}>
						{!isFullscreen && (
							<div class={`${CLNM}-header-left`}>
								<span></span>
								<span></span>
								<span></span>
							</div>
						)}
						<div class={`${CLNM}-header-center`}>260秒，全面了解平台</div>
						<div class={`${CLNM}-header-close`} onClick={close}>
							<CloseOutlined />
						</div>
					</div>
					<div
						class={`${CLNM}-play-content`}
						ref="FullNavRef"
						style={{
							margin: isFullscreen ? 0 : '20px',
							width: isFullscreen ? '100%' : 'calc(100% - 40px)',
							height: isFullscreen ? '100%' : fullNavHeight,
						}}
						onClick={playVieo}
					>
						<div class={`${CLNM}-play-container`}>
							<video
								id={POPUP_VIDEO}
								class={`video-js vjs-default-skin ${CLNM}_1 vjs-big-play-centered`}
								data-setup='{"example_option":true}'
								style={
									!isFullscreen
										? { borderRadius: '8px', objectFit: 'fill' }
										: { objectFit: 'fill' }
								}
								autoplay
								muted
							>
								<source
									src={`${process.env.VUE_APP_CDN_PATH}/video/introduce.mp4`}
									type="video/mp4"
								/>
							</video>
							{!playStatus && (
								<div class={`${CLNM}-play-button`}>
									<div>
										<span class="low-code iconplay_Union"></span>
									</div>
								</div>
							)}
						</div>
					</div>
					<div class={`${CLNM}-footer vjs-control-bar`}>
						<div class={`${CLNM}-footer-left`}>
							<span
								class={
									playStatus
										? 'low-code iconstop_Union'
										: 'low-code iconplay_Union'
								}
								onClick={playVieo}
							></span>
							<span class={`${CLNM}-footer-time`}>
								{showTime.current} /
								{!showTime?.duration.includes('NaN')
									? showTime?.duration
									: '00:00:00'}
							</span>
						</div>
						<div class={`${CLNM}-footer-right`}>
							<span
								class={
									videoNewEl
										? videoNewEl?.muted()
											? 'low-code iconjingyin'
											: 'low-code iconvoice_Union'
										: 'low-code iconjingyin'
								}
								onClick={adjustVolume}
							/>
							<span
								class={
									isFullscreen
										? 'low-code iconzhengchang'
										: 'low-code iconquanping'
								}
								onClick={fullOption}
							/>
						</div>
					</div>
				</div>
			</div>
		)
		const child1 = !visible && dropdown && (
			<div class={CLNM}>
				<ok-avatar
					style={avatarStyle}
					class={`${CLNM}-default_avatar`}
					personInfo={JSONCopy(toRaw(store.state.userInfo))}
					width="32px"
					height="32px"
				></ok-avatar>
			</div>
		)
		return child || child1 || null
	},
})

export default PopupVideo
